# -*- coding: utf-8 -*-
import binascii
import os
import sys
from PySide6.QtCore import Signal, Qt
from PySide6.QtGui import QShortcut, QKeySequence
from PySide6.QtWidgets import QWidget, QMessageBox, QApplication
from loguru import logger

from windowUI.templateUI_ui import Ui_TemplateForm


class TemplateWindow(QWidget, Ui_TemplateForm):
    """
    插件模板
       <h1>1. 标题一<h1>
       <h2>1.2 标题一点一<h2>
       <h1>1. 标题二<h1>
       <h2>1.2 标题二点一<h2>
    """
    # 声明带一个字典类型参数的信号
    templateSignal = Signal(dict)

    def __init__(self):
        super().__init__()
        # 加载UI
        self.setupUi(self)
        # 连接信号与槽
        self.SignalConnectInit()
        # 添加快捷键
        self.ShortcutFun()
        # 引入公共程序
        from utils.common import commonProgram
        # 引入配置文件
        self.myConfig = commonProgram.EnableConfigHandler()
        print('TemplateWindow get config Version', self.myConfig.version)
        # 引入可控串口信息窗口
        self.serialPortWin = commonProgram.EnableFt4222(winSignal=self.templateSignal,
                                                        RecvFt4222Data=self.RecvFt4222Data)
        # 显示窗口
        # self.serialPortWin.show()

    def CleanupSelf(self):
        """
        清理当前窗口并关闭，由其他其他程序调用
        :return:
        """
        try:
            self.close()  # 关闭当前窗口
            self.deleteLater()  # 释放子窗口资源
            print("TpIntWindow.__del__.ok")
        except Exception as err:
            print("TpIntWindow.__del__.error", err)

    def SignalConnectInit(self):
        """
        连接来自UI对象的信号与槽
        :return:
        """
        self.btnHandExec.clicked.connect(self.BtnHandExecFun)

    def BtnHandExecFun(self):
        myData = binascii.hexlify(os.urandom(33)).decode('utf-8')
        self.label.setText(myData)
        dictData = {"data": myData, "type": f"send_tempData", "options": {}}
        self.SendDataHandle(dictData)

    def ShortcutFun(self):
        """
        快捷键 F11 全屏
        快捷键 F5 清屏
        :return:
        """
        # 快捷键 F11
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')
        # 快捷键 F5
        # screenShortcut2 = QShortcut(QKeySequence(Qt.Key_F5), self)
        # screenShortcut2.activated.connect(self.CleanFun)

    def WindowSizeFun(self):
        """
        控制窗口尺寸，此处为原大小（最小UI布局）或者全屏
        :return:
        """
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def SendDataHandle(self, dataDict: dict):
        """
        发送信号或数据处理函数
        :param dataDict:
        :return:
        """
        # 发送信号处理
        dataObj = dataDict.get('data', '')
        typeValue = dataDict.get('type', 'null').strip()
        # 本窗口发送数据
        if "send_" in typeValue:
            self.templateSignal.emit(dataDict)
        elif typeValue != None:
            logger.info(f"dataObj={dataObj}, typeValue={typeValue}")
        # do something

    def RecvFt4222Data(self, dictData: dict):
        """
        用于接收串口控制窗口发过来的信号或数据
        :param dictData:
        :return:
        """
        self.RecvDataHandle(dictData)

    def RecvDataHandle(self, dataDict: dict):
        """
        处理FT4222控制窗口发过来的信号或数据
        :param dataDict:
        :return:
        """
        dataObj = dataDict.get('data', None)
        typeValue = dataDict.get('type', 'null').strip()
        optionsDict = dataDict.get('options', {})
        # 收到信号
        if typeValue == 'send_tempData':
            print(dataObj)
            print(optionsDict)
        if 'TpInt_to_' in typeValue:
            return
        if typeValue == 'status_serial':
            if dataObj == "Serial_Window_Showed":
                pass
            elif dataObj == "Serial_Window_Closed":
                pass
        elif typeValue == 'level_gpio':
            pass
        elif typeValue == 'send_hex':
            pass
        elif typeValue == 'read_hex':
            pass
        elif typeValue == 'rece_protobuf':
            pass
        elif typeValue == 'rece_hex':
            pass
        elif typeValue == 'rece_ascii':
            pass
        elif '_to_TpInt' in typeValue:
            logger.info("收到其他窗口发往Plugin窗口的数据：", typeValue, dataObj)
        # 其他情况
        elif typeValue != None:
            logger.info(f"{typeValue} \t {dataObj}")
        # do something

    def closeEvent(self, event):
        """
        防止误触关闭程序
        :param event:
        :return:
        """
        # 创建一个确认退出的对话框
        reply = QMessageBox.question(
            self, "Confirmation", "Are you sure you want to exit?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No
        )
        if reply == QMessageBox.StandardButton.Yes:
            self.CleanupSelf()
            # 用户确认退出，关闭应用
            event.accept()
        else:
            event.ignore()


# 程序入口，测试当前插件文件使用
if __name__ == "__main__":
    app = QApplication(sys.argv)
    print(TemplateWindow.__name__)
    try:
        class_doc = TemplateWindow().__doc__.strip()
        radio_title = class_doc.splitlines()[0]
        object_name = TemplateWindow().objectName()
        print(object_name,radio_title, class_doc)
    except Exception as err:
        logger.error(err)
    myWindow = TemplateWindow()
    try:
        class_doc = myWindow.__doc__.strip()
        radio_title = class_doc.splitlines()[0]
        print(radio_title, class_doc)
    except Exception as err:
        logger.error(err)
    myWindow.show()
    sys.exit(app.exec())
